package com.cy.src.tcpudp.service.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Created by cy on 16-10-13.
 */

public class UDPService {

    private int BROACTCAST_PORT = 8888;

    public UDPService() {


        try {
            //监听端口
            DatagramSocket datagramSocket = new DatagramSocket(BROACTCAST_PORT);


            //存储接收到数据
            byte data[] = new byte[1024];

            DatagramPacket receiverPacket = new DatagramPacket(data, data.length);

            datagramSocket.receive(receiverPacket);

            receiverPacket.getData();
            int offset = receiverPacket.getOffset();
            int length = receiverPacket.getLength();
            String socketAddress = receiverPacket.getSocketAddress().toString();

            String content = new String(receiverPacket.getData(), receiverPacket.getOffset(), receiverPacket.getOffset() + receiverPacket.getLength());
            System.out.println("收到客户端数据：" + content + "   offset=" + offset + "  length=" + length + "   socketAddress=" + socketAddress);


//            原路返回数据

            InetAddress localhost = InetAddress.getLocalHost();
            byte sendData[] = localhost.getHostAddress().getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receiverPacket.getAddress(), receiverPacket.getPort());
            datagramSocket.send(sendPacket);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        new UDPService();
    }
}
